#include <cstdio>
#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

class SafeFile
{
public:
    //在构造函数中初始化资源
    SafeFile(FILE *fp)
    : _fp(fp)
    {
        cout << "SafeFile(FILE *)" << endl;
        if(nullptr == _fp)
        {
            return;
        }
    }

    //提供若干访问资源的方法
    void write(const string &msg)
    {
        fwrite(msg.c_str(), 1, msg.size(), _fp);
    }

    //在析构函数中回收资源
    ~SafeFile()
    {
        cout << "~SafeFile()" << endl;
        if(_fp)
        {
            fclose(_fp);
            cout << "fclose(_fp)" << endl;
        }
    }

    //不允许复制或者赋值
    SafeFile(const SafeFile &rhs)  = delete;
    SafeFile &operator=(const SafeFile &rhs)  = delete;
private:
    FILE *_fp;
};

void test()
{
    string msg("helloworld\n");
    //利用栈对象的生命周期管理资源,当栈对象在离开作用域的时候
    //会自动执行析构函数
    SafeFile sf(fopen("wd.txt", "a+"));//sf栈对象
    sf.write(msg);
}

void test2()
{
    FILE *fp = fopen("wd2.txt", "a+");
    if(nullptr == fp)
    {
        return;
    }

    string msg("helloworld\n");
    fwrite(msg.c_str(), 1, msg.size(), fp);

    cout << "111" << endl;
    fclose(fp);
    /* while(1){} */
}

int main(int argc, char *argv[])
{
    test2();
    return 0;
}

